(function(){
	
	var elementObject = {
		register:"<div class=\'boxWrapper\'><div class=\'titleHeader\'><p> Registration Section </p></div><div class=\'boxContent\'><div class=\'registrationWrapper\'><form id=\'RegisterForm\' method=\'post\'><p>Username</p><input type=\'text\' id=\'usernameR\' placeholder=\'Username\' required/><br><br><p>Email Address</p><input type=\'email\' id=\'emailR\' placeholder=\'Valid email\' required/><br><br><p>Password</p><input type=\'password\' id=\'passwordR\' placeholder=\'Password\' required/><br><br><p>Verify Password</p><input type=\'password\' id=\'password2R\' placeholder=\'Verify password\' required/><br><br><p>Enter Pin Code</p><input type=\'password\' id=\'pincodeR\' placeholder=\'Pincode\' required/><br><br><button> Sign Up</button></form></div></div></div>",
		update : "<div class='boxWrapper'><div class='titleHeader'><p> Additional Information Required </p></div><div class='boxContent'><div class='registrationWrapper'><form id='updateForm' method='post'><p>Complete Name</p><input type='text' id='rfullName' placeholder='Complete Name' required/><br><br><p>Security Question</p><div id='listSQ'></div><br><br><p>Answer</p><input type='text' id='secAnswer' placeholder='Answer' required/><br><br><button> NEXT</button></form></div></div></div>",
		vote : "<div class='boxWrapper'><div class='titleHeader'><p> Voting Link </p></div><div class='boxContent'><div class='linkWrapper'><h2>Please Select Link to vote</h2><br><select id='linkActive'><option value='1'>GTOP 100</option><option value='2'>EXTREME TOP 100</option><option value='3'>GAMING TOP 100</option><option value='4'>MM TOP 200 </option></select><br><br><button id='voteAction'>Vote Server</button></div></div></div>",
		recover : "<div class='boxWrapper'><div class='titleHeader'><p> Password Recovery Section </p></div><div class='boxContent'><form id='recoverForm' method='post'>Enter Account Username : <input type='text' id='rec_userName' required/> <button>Recover</button></form></div></div>",
		topup : "<div class='boxWrapper'><div class='titleHeader'><p> Top Up Point </p></div><div class='boxContent'><br><p>Please type the code correctly:</p><br><table><tr><td>Serial Number</td><td><input id='topUpCardSN' type='text'/></td></tr><tr><td>Pin Number</td><td><input id='topUpCardPIN' type='text'/></td></tr><tr><td></td><td><button id='topUpCard' >Re-Charge</button></td></tr></table></div></div>",
		login:"<div class='titleHeader'><p> Sign In </p></div><div class='loginBox'><form id='userLogin' method='post'><p>Username</p><input type='text' name='username' id='username' placeholder='Your Username' required/><p>Password</p><input type='password' name='password' id='password' placeholder='Your Password' required/><br><button class='loginButton'>Sign In</button></form><br><br><p id='recoverPass'>Recover My Password ?</p></div>"
	}
	
	
	 $.userAuthProtocol = {
        
        isUserLogin: function(){

                var userID = this.getSession('token'),
                    serial = this.getSession('serial'),
                    newtime     = Math.round(+new Date()/1000),
                    lastLoginTime = this.getSession('lastLogin')+600,
                    formUser =  $("#loginFormH");
                if (userID!=null) {
                    if(lastLoginTime>=newtime){
                        $.userAuthProtocol.setSession('lastLogin',newtime);

                        requireAccess = $.request({route:{app:'authenticate',token:userID,serial:serial}});
                        requireAccess
                                    .done( function( data ){
                                        
                                        
                                        $.userAuthProtocol.setSession('auth',data.auth);
                                         $.checkResponse( data );
                                            
                                            if (typeof(data.Activation) == "undefined"){
                                        
                                            alertify.error("Internal Error");
                                            $.userAuthProtocol.destroySession();
                                            return false;
                                         }
                                        if(data.Activation===0){
                                            //alert("load update");
                                            formUser.empty().html("<div class='titleHeader'><p> Account Information </p></div><div class='userInfoWrapper'><p>waiting for update...</p></div>");
                                            page.empty()
                                                .html(elementObject.update)
                                                .slideDown();
                                            var qLIST= "";
                                                qLIST+="<select id='secQA'>";

                                                qLIST_size = Object.keys(secQ).length;
                                                for(var a=1;a<=qLIST_size;a++){
                                                    qLIST+="<option value="+a+">"+secQ[a]+"</option>";
                                                }
                                                qLIST+="</select>";
                                            $("#listSQ").html(qLIST);
                                            formUser.show();
                                        }else{
                                        	if(data.alert==="1"){
                                        		alertify.log("You have notification", "", 0);
                                        	}
                                            if(data.UserType==="1"){
                                                
                                               formUser.empty().html("<div class='titleHeader'><p> Account Information </p></div><div class='userInfoWrapper'><p>Hello!. <span><b>"+data.userName+"</b></span></p><p>V-Point : <span>"+data.p1+"</span></p><p>E-Point : <span>"+data.p2+"</span></p><p>Last Login : <span>"+data.LastLoginDate+"</span></p><br><select id='menuLoader'><option data-goto='defaultz'>SELECT FUNCTION</option><option data-goto='resetST'>Reset Stats</option><option data-goto='changeSc'>Change School</option><option data-goto='voteForm'>Vote Server</option><option data-goto='voteshop'>Vote Shop</option><option data-goto='premshop'>Premium Shop</option><option data-goto='recharge'>Recharge My Account</option><option data-goto='accPanel'>My Account Settings</option><option data-goto='logout'>Logout My Account</option></select><div id='statusLoader'><img src='./image/loader.gif'></div></div>");
                                                
                                            }else{
                                                
                                                formUser.empty().html("<div class='titleHeader'><p> Account Information </p></div><div class='userInfoWrapper'><p>Hello! [Admin]<span><b>"+data.userName+"</b></span></p><hr><p>V-Point : <span>"+data.p1+"</span></p><p>E-Point : <span>"+data.p2+"</span></p><p>Last Login : <span>"+data.LastLoginDate+"</span></p><br><select id='menuLoader'><option data-goto='defaultz'>SELECT FUNCTION</option><option data-goto='resetST'>Reset Stats</option><option data-goto='changeSc'>Change School</option><option data-goto='voteForm'>Vote Server</option><option data-goto='voteshop'>Vote Shop</option><option data-goto='premshop'>Premium Shop</option><option data-goto='recharge'>Recharge My Account</option><option data-goto='accPanel'>My Account Settings</option><option data-goto='logout'>Logout My Account</option></select><div id='statusLoader'><img src='./image/loader.gif'></div></div>");

                                                pin     =  $.userAuthProtocol.getSession('pin');
                                                $.request({route:{app:'serverstatus'}})
                                                    .then(

                                                        function( data ){
                                                        
                                                            page.empty().html("<div class='boxWrapper'><div class='titleHeader'><p> Admin Panel </p></div><div class='boxRcontent'><table id='serverStatus' border='1'><tbody><tr><td colspan='3'><b>SERVER STATUS</b></td></tr><tr><td>TOTAL ONLINE</td><td>TOTAL ACCOUNT</td><td>TOTAL PLAYERS</td></tr><tr><td>"+data.total_online+"</td><td>"+data.total_cha+"</td><td>"+data.total_acc+"</td></tr></tbody></table><table id='serverStatus'><tbody><tr ><td><i><b>ACCOUNT MANAGER</b></i></td></tr></tbody></table><table id='serverStatus' class='seekResult'><tbody><thead><td>Enter Account Username</td><form method='post'><td><input id='Skusername' required/></td><td><button id='seekUsername'>Search</button></td></form></thead><tbody id='userNameDisplay' style='display:none'></tbody></tbody></table><br><br><table id='serverStatus'><tbody><tr><td><i><b>POINT GENERATOR</b></i></td></tr></tbody></table><table id='serverStatus'><tbody><tr><td><select id='pointOption'><option value='0'>SELECT TYPE </option> <option value='1'>V Point </option><option value='2'>E Point </option></select></td><td>AMOUNT : <input id='evpoint' type='input'/><td><td><button id='generateBtn'>GENERATE</button> <button id='generateView'>VIEW</button><td></tr></tbody></table></div></div>");

                                                        }

                                                );
                                                if(pin==null){
                                                	alertify.prompt("Please Enter your Security Code", function (e, pin) {
														if (e) {
															
															$.userAuthProtocol.setSession('pin',pin);
														} else {
															$.userAuthProtocol.destroySession();
                                                         	location.reload();
														}
													}, "Account Pincode");
                                                   
                                                }
                                                
                                                 formUser.show();
                                                
                                            }
                                        }
                                    })
                                    .fail( function(){
                                        alertify.error("this account is no longer valid");
                                         $.userAuthProtocol.destroySession();
                                         formUser.html(elementObject.login).show();
                                    });
                    }else{
                        
                         $.userAuthProtocol.destroySession();
                        formUser.html(elementObject.login).show();
                    }
                    
                }else{
                    $.userAuthProtocol.destroySession();
                    formUser.html(elementObject.login).show();
                }
        },

        setSession: function( index,value ){
                 store.set(index,value)
        },
        getSession: function( index ){
                return store.get(index);
        },
        delSession: function ( index ){
                store.remove( index );
        },
        destroySession : function (){
            store.clear();
        }

    }
   $("body").delegate("#userLogin","submit",
		function( event ){
		event.preventDefault();
			//alert("disabled");
			//return false;
			if(requestType===1000){
				alertify.error("Request Denied... Please Wait");
				return false;
			}else{
				var username = $("#username").val(),
				password = $("#password").val(),
				time = Math.round(+new Date()/1000);

				alertify.log("connecting to server...");
				//requestType=1000;

				var login = $.request({route:{app:'login',username:username,password:password}});

					login
						.done( function( data ){
							
							if($.checkResponse( data)){
								$.userAuthProtocol.setSession('token',data[0]);
								$.userAuthProtocol.setSession('serial',data[1]);
								$.userAuthProtocol.setSession('lastLogin',time);
                       			$.userAuthProtocol.isUserLogin();
                       			alertify.success("authentication Accepted");
							}
						})
						.fail( function( data ){

							alertify.error( "Server Connection Failed" );
						});
			}
			


	});
	$("body").delegate("#menuLoader","change",function(){
		var loader = $("#statusLoader"),
			action = $(this).find('option:selected').data("goto"),
			token 	=  $.userAuthProtocol.getSession('token');
			if(action==="defaultz"){
				return false;
			}
			loader.fadeIn();

		
		switch( action ){

			case "logout" : 
						$.userAuthProtocol.destroySession();
						 window.location.href = location.href;
						
				break;
			case "voteshop"	:
						
						$.request({route:{app:'itemshop',mode:2}})
							.done( function( data ){
								
								
								var storeSize = data.length;

								

								storeElement= "<div class='boxWrapper'><div class='titleHeader'><p> Vote Shop </p></div><div class='shopController'><select><option>Select Category</option><option>Select Category</option><option>Select Category</option><option>Select Category</option></select> <input id='searchSTR' type='text'/> <button id='searchItem' data-mode='2'>Search</button></div><div class='boxContent shop'><ul class='storeItem'>";

								
								
								for(var a=0; a<storeSize;a++){

									storeElement+="<li><div class='itemWrapper'><div class='itemICO'><img src='image/item/sample.jpg' alt='item' /></div><p>"+data[a].ItemName+"</p><p>Price : "+data[a].ItemPrice+"</p><button data-item='"+data[a].ProductNum+"' data-mode='2' id='buyItem'>BUY</button></div></li>";

								}

								storeElement+="</ul></div></div>"; 

								page.empty().html(storeElement)
										.slideDown();
										loader.hide();

							})
							.fail( function( data ){

			 					alertify.error("server failed to response");

			 				});
					break;
			case "premshop" :
						$.request({route:{app:'itemshop',mode:1}})
							.done( function( data ){
								
								var storeSize = data.length;

								

								storeElement= "<div class='boxWrapper'><div class='titleHeader'><p> Premium Shop </p></div><div class='shopController'><select><option>Select Category</option><option>Select Category</option><option>Select Category</option><option>Select Category</option></select> <input id='searchSTR' type='text'/> <button id='searchItem' data-mode='1' >Search</button></div><div class='boxContent shop'><ul class='storeItem'>";

								
								
								for(var a=0; a<storeSize;a++){

									storeElement+="<li><div class='itemWrapper'><div class='itemICO'><img src='image/item/sample.jpg' alt='item' /></div><p>"+data[a].ItemName+"</p><p>Price : "+data[a].ItemPrice+"</p><button data-item='"+data[a].ProductNum+"' data-mode='1' id='buyItem'>BUY</button></div></li>";

								}

								storeElement+="</ul></div></div>"; 

								page.empty().html(storeElement)
										.slideDown();
										loader.hide();

								//storeElement+= ""; 





							})
							.fail( function( data ){

			 					alertify.error("server failed to response");

			 				});
				break;
			case "recharge":
				page.empty().html(elementObject.topup)
										.slideDown();
										loader.hide();
				break;
			case "resetST" :
					$.request({route:{app:'checkpoint',type:action,token:token}})
						.done( function( data ){
							
								if($.checkResponse( data )){
								var chaCount = data.length,
									chaList="";

									chaList+="<div class='boxWrapper'><div class='titleHeader'><p> RESET STATS </p></div><div class='resetBoxWrapper'><h2>Please Select Character to Reset Stats</h2><br><select id='chaID'>";

									for(var a=0;a<chaCount;a++){
										
										chaList+="<option value='"+data[a].ChaNum+"'>"+data[a].ChaName+"</option>";
									
									}

									chaList+="</select><br><br><button id='resetAction'>Reset Stats</button><br><br></div></div>";

									page.empty().html(chaList)
										.slideDown();
										loader.hide();
							}
								
						})
						.fail( function( data ){

	 						alertify.error("server failed to response");

		 				});
				break;

				case "changeSc" :
					
					$.request({route:{app:'checkpoint',type:action,token:token}})
						.done( function( data ){
								 
								if($.checkResponse( data )){
								var chaCount = data.length,
									chaList="";

									chaList+="<div class='boxWrapper'><div class='titleHeader'><p> Change School </p></div><div class='resetBoxWrapper'><h2>Please Select Character to Reset Stats</h2><br><select id='chaID'>";

									for(var a=0;a<chaCount;a++){
										
										chaList+="<option value='"+data[a].ChaNum+"'>"+data[a].ChaName+"</option>";
									
									}


									chaList+="</select><br><br><select id='schoolActive'><option value='0'>SG Campus</option><option value='1'>MP Campus</option><option value='2'>PHNX Campus</option></select><br><br><br><button id='changeAction'>Change</button><br><br></div></div>";

									page.empty().html(chaList)
										.slideDown();
										loader.hide();
							}
								
						})
						.fail( function( data ){

	 						alertify.error("server failed to response");

		 				});



					break;
				case "voteForm" :

					page.empty().html(elementObject.vote)
										.slideDown();
										loader.hide();

					break;
				case "accPanel" :
					var token 	=$.userAuthProtocol.getSession('token');
					$.request({route:{app:'userinfo',token:token}})
						.done( function( data ){
								
							
							var gt_H = Math.floor(data.GameTime3 / 60),
								gt_M = data.GameTime3 - 60 * gt_H,
								character = (data.Character>0) ? "<p>"+data.Character+" Characters</p></div><div class='lfloat'><span id='viewChaInfo'>View</span>" : "<p>No Character Found</p></div><div class='lfloat'>";
							

							status=(data.status==="1") ? "Connected" : "Disconnected";
							discBtn=(data.status==="1") ? "<button id='userFixNow'>Disconnect</button>" : "";
							page.empty().html("<div class='boxWrapper'><div class='titleHeader'><p> General Account Settings </p></div><div class='boxContent'><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>Name </p></div><div class='LinfoSection2 lfloat'><p>"+data.name+" </p></div><div class='lfloat'></div></div><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>Username </p></div><div class='LinfoSection2 lfloat'><p>"+data.id+" </p></div><div class='lfloat'></div></div><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>Email </p></div><div class='LinfoSection2 lfloat'><p>"+data.email+"</p></div><div class='lfloat'></div></div><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>Date Registered </p></div><div class='LinfoSection2 lfloat'><p>"+data.date+"</p></div><div class='lfloat'></div></div><div class='accInfoWrapper'><div id='ui_PassForm'><div class='LinfoSection lfloat'><p>Password </p></div><div class='LinfoSection2 lfloat'><p>*********</p></div><div class='lfloat'><span id='uiToggleEvent' data-uitype='chPass' class='miniToggle_btn'>Edit Password</span></div></div><div class='clearfix'> </div><div id='ui_chPassFormManager' class='changePassWrapper' style='display:none'><div class='LinfoSection lfloat'>Password</div><div class='LinfoSection2 lfloat'><p>Current</p><form id='chPassSave' method='post'><input id='chpass1' type='password' required/><br><br><p>New</p><input id='chpass2' type='password' required/><br><br><p>Re-type new</p><input id='chpass3' type='password' required/><br><br><p>Enter Pincode</p><input id='chpass4' type='password' required/><br><br><button id='chPassSave'>Save</button> </form></div></div></div><div class='accInfoWrapper'><div id='ui_PassForm'><div class='LinfoSection lfloat'><p>Pincode </p></div><div class='LinfoSection2 lfloat'><p>*********</p></div><div class='lfloat'><span id='uiToggleEvent' data-uitype='chPin' class='miniToggle_btn'>Edit Pincode</span></div></div><div class='clearfix'> </div><div id='ui_chPinFormManager' class='changePassWrapper' style='display:none'><div class='LinfoSection lfloat'>Pincode</div><div class='LinfoSection2 lfloat'><p>Current</p><form id='chPinSave' method='post'><input id='chpin1' type='password' required/><br><br><p>New</p><input id='chpin2' type='password' required/><br><br><p>Re-type new</p><input id='chpin3' type='password' required/><br><br><button>Save</button> </form></div></div></div><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>GameTime</p></div><div class='LinfoSection2 lfloat'><p>"+gt_H+" Hour and "+gt_M+" Minutes</p></div><div class='lfloat'></div></div><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>My Character</p></div><div class='LinfoSection2 lfloat'>"+character+"</div></div><div class='accInfoWrapper'><div class='LinfoSection lfloat'><p>Account Status</p></div><div class='LinfoSection2 lfloat'><p class='"+status+"'>"+status+"</p></div><div class='lfloat'>"+discBtn+"</div></div></div></div>")
							.slideDown();
							loader.hide();
						});
					
					break;
			default :
					alertify.error("unhandle process");
				break;
		}
	});
	$("body").delegate("#recoverPass",
				"click", function(){
				page.empty().html(elementObject.recover)
				.slideDown();
		
	})

	page.delegate("#topUpCard","click", function(){
	
		var sn		= $("#topUpCardSN").val(),
			pn 		= $("#topUpCardPIN").val(),
			token 	=$.userAuthProtocol.getSession('token');

			if( sn=="" || pn==""){

				alertify.error("All field are required");

				return false;
			}

			$.request({route:{app:'topup',sn:sn,pn:pn,token:token}})

				.then(
					function( data ){
						
						if($.checkResponse( data )){
							alertify.success("Point Inserted...");
							$.userAuthProtocol.isUserLogin();  //after success call userlogin prototype//
							page.slideUp();
						}

					},
					function(){
						alertify.error("unhandle process");
					}
				);



	});
	//view character info event
	page.delegate("#viewChaInfo","click",function(){

		var token 	=$.userAuthProtocol.getSession('token'),
			chaInfoElem="";

			chaInfoElem+="<div class='boxWrapper'><div class='titleHeader'><p> My Character </p></div><div class='boxContent'><table><tr><td>Character Name</td><td>Gold</td><td>Class</td><td>School</td><td>Kill</td><td>Death</td><td>Status</td></tr><tbody>";

			$.request({route:{app:'characterData',token:token}})
				.then(
					function( data ){
						
						var chaSize  = data.length;
							

						for(var a=0; a<chaSize ; a++){
							status  = (data[a].ChaOnline==0) ? "Offline" : "Online";
							chaInfoElem+="<tr><td>"+(a+1)+". "+data[a].ChaName+"</td><td>"+data[a].ChaMoney+"</td><td>"+ranclass[data[a].ChaClass]+"</td><td>"+school[data[a].ChaSchool]+"</td><td>"+data[a].ChaPkWin+"</td><td>"+data[a].ChaPkLoss+"</td><td>"+status+"</td></tr>";

						}
						
							chaInfoElem+="</tbody></table></div></div>";
							
							page.html( chaInfoElem )
								.slideDown();
					},

					function(){

						alertify.error("Server Failed to response.. Please try again later.");
					}
				);


	})
	page.delegate("#claimRewards","click",function(){
		var token 	=$.userAuthProtocol.getSession('token');

			$.request({route:{app:'gametime',token:token}})
				.then( 

					function( data ){

						
						
						if($.checkResponse( data )){

									alertify.success("Game Time Collected....");
									
									$.userAuthProtocol.isUserLogin();  //after success call userlogin prototype//
									page.slideUp();
						}

					},

					function(){

						alertity.error("Server Failed to response.. Please try again later.");
					}


				);

		
	})
	page.delegate("#generateView","click", function(){
		var token 	=$.userAuthProtocol.getSession('token'),
			auth 	=$.userAuthProtocol.getSession('auth'),
			pin 	=$.userAuthProtocol.getSession('pin');
			
			$.request({route:{app:'viewPoint',token:token,auth:auth,pin:pin}})
				.then(
					function( data ){
						if($.checkResponse( data )){
							var viewPointElem ="";
							viewPointElem+="<div class='boxWrapper'><div class='titleHeader'><p> Available Point </p></div><div class='boxContent'><br><table class='table' border='1'><tr><td>&nbsp; Serial</td><td>&nbsp; Pin</td><td>&nbsp; Amount</td><td>&nbsp; Type</td></tr>";

							var nSize = data.length;

							for(var a=0; a<nSize ; a++){
								var type = (data[a].type==1) ? "Vote Point" : "E Point";
								
								viewPointElem+="<tr><td>&nbsp; "+data[a].serial+"</td><td>&nbsp; "+data[a].pin+"</td><td>&nbsp; "+data[a].amount+"</td><td>&nbsp; "+type+"</td></tr>";

							}
							viewPointElem+="</table><br><br><button id='generateView'>Refresh</button></div></div>";

							page.html( viewPointElem )
								.slideDown();
								
						}
						

					},
					function(){

						alertify.error("Unable to handle request");
					}
				);
	})
	page.delegate("#generateBtn","click", function(){
		var point 	= $("#evpoint").val(),
			type  	= $("#pointOption").val(),
			token 	=$.userAuthProtocol.getSession('token'),
			auth 	=$.userAuthProtocol.getSession('auth'),
			pin 	=$.userAuthProtocol.getSession('pin');

			if(type>0){
				if(point!="" && point>0){

					$.request({route:{app:'generaPoint',type:type,point:point,token:token,auth:auth,pin:pin}})
						.then( 

							function( data ){
								if($.checkResponse( data )){
									console.log( data );
									alertify.success("Point Generated");
									$("#evpoint").val(0);
								}
								
							},

							function(){

								alertify.error("Request Denied or failed");
							}

						);

				}else{
					alertify.error("Please Enter Amount greater than 0");
				}
			}else{
				alertify.error("Please select proper point....");
			}
	})
	page.delegate("#Skusername","keyup",function( event ){

		if(event.keyCode!=13){
			$("#userNameDisplay").slideUp();
		}
		
	})
	page.delegate("#seekUsername","click",function( event ){
		event.preventDefault();
		
		var username = $("#Skusername").val();
		if(username==""){
			alertify.error("Username field cannot be empty");
		}else{
				var token 	=$.userAuthProtocol.getSession('token'),
					auth 	=$.userAuthProtocol.getSession('auth'),
					pin 	=$.userAuthProtocol.getSession('pin');
				$.request({route:{app:'admin_searchUserInfo',username:username,token:token,auth:auth,pin:pin}})
					.then(

						function( data ){

								
							if($.checkResponse( data )){
								
								var ele = $("#userNameDisplay")
								
								ele.html("<tr><td>Name</td><td>"+data.Name+"</td><td></td><td></td></tr><tr><td>UserNum</td><td>"+data.UserNum+"</td><td></td><td></td></tr><tr><td>UserName</td><td>"+data.Username+"</td><td></td></tr><tr><td>User Type</td><td>"+data.UserType+"</td><td></td></tr><tr><td>V Point</td><td>"+data.vPoint+"</td><td class='addPointer' data-user='"+data.UserNum+"' id='changeVpoint'>Add V Point</td></tr><tr><td>E Point</td><td>"+data.ePoint+"</td><td class='addPointer' data-user='"+data.UserNum+"' id='changeEpoint'>Add E Point</td></tr>");	

								ele.slideDown();
								
							}
						},
						function(){

							alertify.error("Request Denied or failed");
						}

					);


			
		}

		
	});
	page.delegate("#changeVpoint","click",function(){

		var token 	=$.userAuthProtocol.getSession('token'),
			auth 	=$.userAuthProtocol.getSession('auth'),
			pin 	=$.userAuthProtocol.getSession('pin'),
			userNum =$(this).data("user");
		
		var point = prompt("Please enter Additional V Point", "0");
			if(point>0){
			$.request({route:{app:'addVpoint',token:token,auth:auth,pin:pin,userNum:userNum,point:point}})
				.then(

					function( data ){

						if($.checkResponse( data )){

							alertify.success("Point Inserted");
							

						}
						
					},

					function(){

						alertify.error("Request Denied or Failed");
					}

				);
			}
		
	})
	page.delegate("#changeEpoint","click",function(){

		var token 	=$.userAuthProtocol.getSession('token'),
			auth 	=$.userAuthProtocol.getSession('auth'),
			pin 	=$.userAuthProtocol.getSession('pin'),
			userNum =$(this).data("user");
		
		var point = prompt("Please enter Additional V Point", "0");
       
			if(point>0){
			$.request({route:{app:'addEpoint',token:token,auth:auth,pin:pin,userNum:userNum,point:point}})
				.then(

					function( data ){

						


						if($.checkResponse( data )){

							alertify.success("Point Inserted");
							

						}
						
					},

					function(){

						alertify.error("Request Denied or Failed");
					}

				);
			}
		
	})
	page.delegate("#userFixNow","click",function(){
		var token 	= $.userAuthProtocol.getSession('token');
			$.request({route:{app:'userfix',token:token}})
				.then( 
					function( data ){

						if($.checkResponse( data )){

							alertify.success("Account Disconnected");
							$.userAuthProtocol.destroySession();
							page.slideUp();

						}

					}
				);
	})
	page.delegate("#recoverForm","submit",function( event ){

		event.preventDefault();

		var username = $("#rec_userName").val(),
			token 	=$.userAuthProtocol.getSession('token');

			if(token==null){

					$.request({route:{app:'recoverpass',username:username}})
						.then(

							//success call back//
							function( data ){

								if($.checkResponse( data )){
									$.userAuthProtocol.setSession('token',data.id);
									page.empty().html("<div class='boxWrapper'><div class='titleHeader'><p> Account Verification System </p></div><div class='boxContent'><form id='recoverFormVerify' method='post'><br><p>SECURITY QUESTION :</p><br><p>"+secQ[data.q]+"</p><br><br>Please Enter Answer : <input type='text' id='rec_answer' required/> <button>Recover</button></form></div></div>")
									.slideDown();
								}

							},

							//error call back
							function(){

								alertify.error("Request fail.. please refresh your browser");

							}




						);
				
			}else{

				alertify.error("Your other account is connected.. Please log out to continue");
			}


	});
	page.delegate("#recoverFormVerify","submit",function( event ){

		event.preventDefault();

		var sec_answer 	= $("#rec_answer").val(),
			token 		= $.userAuthProtocol.getSession('token');

		$.request({route:{app:'verifyAnswer',answer:sec_answer,token:token}})
			.then(

				function( data ){

						
						if($.checkResponse( data )){
						
							alertify.log("Your new Password is: "+data+"<br> Please click to close", "", 0);
							page.empty();
						}

				},

				function(){

					alertify.error(" Server failed to response, Please try Again!.");
				}


			);


	});
	page.delegate("#chPassSave","submit",function( event ){

		event.preventDefault();
		var current =$("#chpass1").val(),
			newp 	=$("#chpass2").val(),
			newp2 	=$("#chpass3").val(),
			pin 	=$("#chpass4").val(),
			token 	=$.userAuthProtocol.getSession('token');

			if(newp===newp2){
				if(current===newp){
					alertify.error("Please try another Password...");
				}else{

					$.request({route:{app:'changepass',old:current,pass:newp,pin:pin,token:token}})
					.done( function( data ){
							
						if($.checkResponse( data )){
						
							alertify.success("Change Password Success");
							$.userAuthProtocol.destroySession();
							location.reload();
						}
						

					})
					.fail( function(){
						
						alertify.error("server failed to response");

					});
				}
				
			}else{
				alertify.error(" Password Mismatch");
			}
	});
	page.delegate("#chPinSave","submit",function( event ){

		event.preventDefault();

		var current =$("#chpin1").val(),
			newp 	=$("#chpin2").val(),
			newp2 	=$("#chpin3").val(),
			token 	=$.userAuthProtocol.getSession('token');
			if(newp===newp2){
				if(current===newp){
					alertify.error("Please try another Pincode...");
				}else{

					$.request({route:{app:'changepin',old:current,pin:newp,token:token}})
						.done( function( data ){
							
							if($.checkResponse( data )){
							
								alertify.success("Change Pincode Success");
								$.userAuthProtocol.destroySession();
								location.reload();
							}
							

						})
						.fail( function(){
							
							alertify.error("server failed to response");

						});
				}
				
			}else{
				alertify.error(" Pincode Mismatch");
			}

		
	});
	page.delegate("#uiToggleEvent","click",function(){

		var eventType = $(this).data("uitype");
						$(this).parents("#ui_PassForm").hide();
		switch( eventType ){

			case "chPass" :
				$("#ui_chPassFormManager").fadeIn();
				break;
			case "chPin" :
				$("#ui_chPinFormManager").fadeIn();
				break;
			default:
				return false;
				break;
		}

	});
	page.delegate("#voteAction","click",function(){

		var link = $("#linkActive").val(),
			token 	=$.userAuthProtocol.getSession('token');

			
			window.open(votelink[link], "_blank");

			$.request({route:{app:'votelink',token:token,link:link}})
				.done( function( data ){
					if($.checkResponse( data )){
						
						alertify.success("Vote Success");
						$.userAuthProtocol.isUserLogin();
						
					}
					

				})
				.fail( function( data ){

 						alertify.error("server failed to response");

	 			});
	});
	page.delegate("#searchItem","click",function(){

		var strItem 	= $("#searchSTR").val(),
			mode 		= $(this).data("mode");

 			$.request({route:{app:'searchItem',mode:mode,strItem:strItem}})
 				.done( function( data ){	

 					var storeSize = data.length,
 						fragments = $(".storeItem"),
 						storeElement="";

 						if(storeSize>0){
	 						
	 						for(var a=0;a<storeSize;a++){
	 							
	 							storeElement+="<li><div class='itemWrapper'><div class='itemICO'><img src='image/item/sample.jpg' alt='item' /></div><p>"+data[a].ItemName+"</p><p>Price : "+data[a].ItemPrice+"</p><button data-mode="+mode+" data-item='"+data[a].ProductNum+"' id='buyItem'>BUY</button></div></li>";

	 						}

	 						fragments.empty()
 							.html( storeElement );
 						}else{

 							fragments.empty();
 							alertify.error("Unable to find :"+strItem);

 						}
 						

 				})
 				.fail( function( data ){

 					alertify.error("server failed to response");

 				});

	});
	page.delegate("#changeAction","click",function(){
	var	token 	=$.userAuthProtocol.getSession('token'),
		chaID = $("#chaID").val(),
		school 	=$("#schoolActive").val();

		$.request({route:{app:'changeschool',token:token,chaID:chaID,school:school}})
			.done( function( data ){

				if($.checkResponse( data )){
							
					alertify.success("Reset Success");
					$.userAuthProtocol.isUserLogin();
					page.slideUp();
				}
			})
			.fail( function( data ){

 					alertify.error("server failed to response");

 				});
	})
	page.delegate("#buyItem","click",function(){
		token 	=$.userAuthProtocol.getSession('token'),
		n 		=$(this).data('item');
		mode 	=$(this).data('mode');

				$.request({route:{app:'buyitem',n:n,token:token,mode:mode}})
					.done( function( data ){

						if($.checkResponse( data )){
							if( data ==="ok"){
								$.userAuthProtocol.isUserLogin();
								alertify.confirm("Item Purchase Sucess....Continue Shopping?", function (e) {

									if (!e) {
										
										page.slideUp();

									} 
								});

							}
						}
						
					})
					.fail( function(){

						alertify.error("server failed to response");
					});


	})
	page.delegate("#resetAction","click",function(){
		var chaID = $("#chaID").val(),
			token 	=  $.userAuthProtocol.getSession('token');
		if(chaID!=null){

				$.request({route:{app:'resetStats',chaID:chaID,token:token}})
					.done( function( data ){
						if($.checkResponse( data )){
							
							alertify.success("Reset Success");
							$.userAuthProtocol.isUserLogin();
							page.slideUp();
						}
						
					})
					.fail( function(){

						alertify.error("Server failed to response your request");
					});

		}else{

			alertify.error("Problem found.. please contact administrator");
		}
	});

	page.delegate("#RegisterForm","submit",function( event ){
		event.preventDefault();

		if(requestType===1001){
				alertify.error("Request Denied... Please Wait");
				return false;
			}else{
				//requestType=1001;
				var username = $("#usernameR").val(),
					email 	= $("#emailR").val(),
					password = $("#passwordR").val(),
					password2 = $("#password2R").val(),va
					pincode = $("#pincodeR").val();

					if(password!=password2){
						alertify.error(" Please verify Password correctly..");
						return false
					}
					userRegister = $.request({route:{app:'register',username:username,email:email,password:password,pincode:pincode}});

					userRegister
							.done( function( data ){
								
								if($.checkResponse( data)){
									alertify.success("Registration Success");
									page.slideUp();
									
								}
							})
							.fail( function(){
								alertify.error("Server connection failed");
							});	
					
					
			}

	});
	page.delegate("#updateForm","submit", function( event ){
		event.preventDefault();
		var fullname = $("#rfullName").val(),
			secQ	 = $("#secQA").val(),
			secA 	 = $("#secAnswer").val(),
			token 	=  $.userAuthProtocol.getSession('token');

			 $.request({route:{app:'update',fullname:fullname,secQ:secQ,secA:secA,token:token}})
			  	.done( function( data ){
			  		console.log( data );
			  		if( data==="success"){
			  			$.userAuthProtocol.isUserLogin();
			  			page.slideUp();
			  			alertify.success("Profile Updated!.");
			  		}
			  	})
			  	.fail( function(){
			  			alertify.error("unable to process updates");
			  	});
	})
	var menu = $(".menuButton");
		menu.click( function(){
			alertify.log("Processing....");
		var menuType = $(this).data("nav"),
			els = $(this);
			


			var k=page.slideUp().promise();
			

			els.parent().find("li").children().removeClass("btnActive");
			els.children().addClass("btnActive");	
			

		switch(menuType){

			case 1:
				location.reload();		
				break;
			case 2:
				alert("not in service");

				break;
			case 3:
				k.done(function(){
					$.rankhelper( 0 );
				});
				break;
		
			case 31:
					$.rankhelper( 31 ); //archer M/ F
				break;
			case 32:
					$.rankhelper( 32 ); //swordie M/F
				break;
			case 33:
					$.rankhelper( 33 );  //shaman M/F
				break;
			case 34:
					$.rankhelper( 34 );  //brawler M/F
				break;s
			case 5:
					
					k.done(function(){
						var req = $.request({route:{app:'download'}});
							req
								.done( function( data ){
									
									
									var dlElement="";
										dlElement+="<div class=\'boxWrapper\'><div class=\'titleHeader\'><p> Download Section </p></div><div class=\'boxContent\'><ul class=\'newsList\'>";


									var reqSize = data.length;	

									for(var a=0; a<reqSize;a++){

										dlElement+="<li><div class=\'dlWrapper\'><div class=\'iconWrapper lfloat\'><a target='_blank' href=\'"+data[a].linkAddress+"\'><img src=\'image/dl-icon.png\'/></a></div><div class=\'dlInformation lfloat\'><h2>"+data[a].linkName+"</h2><p><img src=\'image/info-icon.png\' alt=\'icon\'/><i> uploaded: "+data[a].dateUpload+" (click icon to download)</i></p></div></div></li>";
									}
									
									dlElement+="</ul><div class=\'dlNotice\'><p>To speed up download. We recommend using Internet Download Manager</p></div></div></div>";

									page
										.empty()
										.html(dlElement)
										.slideDown();
										
								})
								.fail( function(){
									alertify.error("data request failed");
								});
						
					});
					
				break;
			case 6:
				k.done(function(){

					page.empty()
						.html(elementObject.register)
						.slideDown();
						var scrollto = this.offset().top - 10;
					   $('html,body').animate({
					     scrollTop: scrollto
					   },1000);
				});
				break;

			default:
				console.log( menuType);
				
				break;
		}

	});

$.userAuthProtocol.isUserLogin();

		
})();
